<template>
	<view class="page">
		<wd-form ref="form" :model="info">
			<wd-cell-group border>
				<wd-input label="用户手机号" label-width="100px" prop="phone" v-model="info.phone" disabled placeholder="用户手机号"
					:rules="[{ required: true, message: '请填写手机号' }]" />
				<wd-picker label="发放的券" v-if="coupons.length" label-width="100px" prop="coupons_id" v-model="info.coupons_id"
					:columns="coupons" placeholder="请选择券" :rules="[{ required: true, message: '请选择券' }]" />
					<wd-cell title="数量" title-width="100px" prop="number">
						<view style="text-align: left">
							<wd-input-number v-model="info.number" :rules="[{ required: true, message: '请填写发放数量' }]" />
						</view>
					</wd-cell>
			</wd-cell-group>
			
			<view class="footer">
				<wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
			</view>
		</wd-form>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from "vue";
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import apiUser from "@/api/user.js"
	const coupons = ref([])
	const info = reactive({
		phone: "",
		coupons_id: null,
		number: 1
	})
	
	let id = null
	
	onLoad((e) => {
		id = e.id
		info.phone = e.phone
	})
	

	const getCouponList = () => {
		apiUser.getMtCoupon({
			merchantId: 1
		}).then(res => {
			let list = []
			res.coupon.content.map(item => {
				list.push({
					label: `${item.name}-${item.type}`,
					value: item.id
				})
			})
			coupons.value = list
		})
	}

	const handleSubmit = () => {
		if(info.coupons_id == null) {
			uni.showToast({
				icon: "none",
				title: "请选择需要下发的券种"
			})
			return 
		}
		
		apiUser.putCoupon({
		    couponId: info.coupons_id,
		    userId: id,
		    number: info.number
		}).then(res => {

		    if (res) {
		        uni.showToast({
		            icon: "none",
		            title: "下发成功"
		        })
		    } else {
		        uni.showToast({
		            icon: "none",
		            title: "出现错误，请稍后再试"
		        })
		    }
		
		    setTimeout(() => {
		        uni.navigateBack()
		    }, 500)
		})
	}

	getCouponList()
</script>

<style lang="scss" scoped>
	.page {
		padding: 20rpx;
	}

	.footer {
		margin-top: 120rpx;
	}
</style>